<template>
  <div class="normalMaintenanceStandardDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="formData"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code"> 评级标准 {{ formData.code || "" }}</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="titleEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!-- <label>参数组名称</label> -->
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend" style="color: red"
              >标题</template
            ></el-input
          >
        </div>
      </div>
      <dividerTitle :title="'基本信息'"></dividerTitle>
      <editForm
        :formConfig="basicConfig"
        ref="basicForm"
        :formData="formData"
      ></editForm>
      <tableList
        :allInfo="formData"
        :isEditTable="isEditTable"
        ref="tableList"
      ></tableList>
    </editPageNew>
  </div>
</template>
<script>
import {
  queryRatingDetail,
  addRating,
  updateRating,
  setStandardStatus,
  deleteRating,
} from "@/api/standardManagement/ratingStandard.js";
import tableList from "./tableList.vue";
export default {
  components: { tableList },
  data() {
    return {
      titleName: "",
      showInput: false,
      isEditTable: true,
      titleEdit: true,
      userInput: false,
      creatInfo: {},
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
      basicConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "适用范围:",
            prop: "appName",
            type: "text",
            trigger: "change",
            span: 6,
            disabled: true,
          },
          {
            label: "设备分类:",
            prop: "typeName",
            idsStr: "typeId",
            type: "deviceClassify",
            required: true,
            disabled: false,
            span: 6,
            methods: (data) => {
              this.producedTitle(data[0].name);
            },
          },
        ],
      },
      formData: {},
      tableConfig: {
        tableData: [],
      },
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "发布",
          icon: "el-icon-top-right",
          hide:
            ["details", "perform"].includes(this.pageType) ||
            this.formData.status != 0,
          // content: "未授权功能",
          // disabled: !this.$store.getters.isBtnAuth("release"),
          methods: () => {
            this.release();
          },
        },
        {
          text: "取消发布",
          icon: "el-icon-close",
          hide: this.formData.status != 1,
          // content: "未授权功能",
          // disabled: !this.$store.getters.isBtnAuth("unRelease"),
          methods: () => {
            this.unRelease();
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) ||
            this.formData.status == 1,
          // content: "未授权功能",
          // disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["perform", "add"].includes(this.pageType) ||
            this.formData.status == 1,
          // content: "未授权功能",
          // disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {
        nowStep: this.formData.status, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "已发布"],
      };
      return obj;
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    //初始化详情页
    init() {
      let { id, deviceId, deviceName } = this.$route.query;
      if (id) {
        this.pageType = "edit";
        // this.pageType = this.$store.getters.isBtnAuth("edit")
        //   ? "edit"
        //   : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
          this.titleEdit = false;
          this.isEditTable = false;
        }
      } else {
        this.pageType = "add";
        this.showInput = true;
        this.$set(
          this.formData,
          "appid",
          this.$store.state.user.userInfo.appId
        );
        this.$set(
          this.formData,
          "appName",
          this.$store.state.user.userInfo.appName
        );
        this.$set(this.formData, "typeId", deviceId);
        this.$set(this.formData, "typeName", deviceName);
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.showInput = true;
        this.$message.warning("标题不能为空");
      }
    },
    //手动输入标题
    userInputTitle(val) {
      if (val != "") {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    },
    //初始化标题生成方式
    initTitleInput(formData) {
      let title = `${formData.deptName}${formData.typeName}评级标准`;
      if (formData.name != title) {
        this.userInput = true;
      }
    },
    //生成标题
    producedTitle(name) {
      let orgName = this.$store.getters.currentOrgInfo.name;
      let title = `${orgName}${name}评级标准`;
      if (!this.userInput) {
        this.titleName = title;
      }
    },
    //获取标准详情
    getDetails(id) {
      queryRatingDetail({ id: id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          this.creatInfo = res.data;
          this.titleName = this.formData.name;
          this.stepLevel = res.data.stepLevel;
          this.initTitleInput(this.formData);
          if (this.pageType != "detail") {
            if (this.formData.status) {
              this.isEditTable = false;
              this.titleEdit = false;
              this.basicConfig.itemArr[1].disabled = true;
            } else {
              this.isEditTable = true;
              this.titleEdit = true;
              this.basicConfig.itemArr[1].disabled = false;
            }
          }
        }
      });
    },
    //发布
    async release() {
      try {
        let formData = await this.$refs.basicForm.getFormData();
        let tableData = this.$refs.tableList.getItemData();
        formData.items = tableData;
        formData.name = this.titleName;
        formData.status = 1;
        let res;
        if (!tableData) {
          this.$message.warning("评级标准不能为空");
        } else if (formData.name == "") {
          this.loseFocus();
        } else {
          res = await updateRating(formData);
          this.$message.success(res.description);
          this.$utils.addOperateLog(this.formData.id, `发布了评级标准`);
          this.getDetails(this.formData.id);
          this.updateListData();
        }
      } catch (error) {
        console.log(error);
      }
    },
    //取消发布
    unRelease() {
      const params = {
        id: this.formData.id,
        status: 0,
      };
      setStandardStatus(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("取消发布成功");
          this.$utils.addOperateLog(this.formData.id, `取消发布了评级标准`);
          this.getDetails(this.formData.id);
          this.updateListData();
        }
      });
    },
    deleteId() {
      this.$confirm("确定要删除选中数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteRating({ ids: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(this.formData.id, `删除了评级标准`);
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存正常维护标准
    async save() {
      try {
        let formData = await this.$refs.basicForm.getFormData();
        let tableData = this.$refs.tableList.getItemData();
        formData.items = tableData;
        formData.name = this.titleName;
        formData.status = 0;
        let res;
        if (!tableData) {
          this.$message.warning("评级标准不能为空");
        } else if (formData.name == "") {
          this.$message.warning("标题名称不能为空");
        } else {
          if (this.pageType == "add") {
            res = await addRating(formData);
            this.$message.success(res.description);
            this.$utils.addOperateLog(res.data, `新建了评级标准`);
            this.updateListData();
            let obj = {
              id: res.data,
              pageType: "edit",
            };
            this.$router.push({
              query: obj,
            });
          } else {
            res = await updateRating(formData);
            this.$message.success(res.description);
            this.$utils.addOperateLog(this.formData.id, `修改了评级标准`);
            this.getDetails(this.formData.id);
            this.updateListData();
          }
        }
      } catch (error) {}
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.normalMaintenanceStandardDetails {
  // overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
</style>